﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Messaging;
using JustinAngel.UnitedNationsNews.Framework;
using Microsoft.Phone.Controls;
using JustinAngel.Neurons.Framework.Helpers;
using Microsoft.Phone.Shell;

namespace JustinAngel.UnitedNationsNews.Pages.Article
{
    public partial class ArticlePage : BasePage
    {

        public ArticlePage()
        {
            InitializeComponent();
            iconPlay = (ApplicationBarIconButton) this.ApplicationBar.Buttons[0];
            iconPause = (ApplicationBarIconButton) this.ApplicationBar.Buttons[1];

            IoC.Get<IMessenger>().Register<ArticleFocusOnParagraphMessage>(this, OnArticleFocusOnParagraph);
            
            IoC.Get<IMessenger>().Register<ArticleTextToSpeechStartedOrPause>(this, OnArticleTextToSpeechStartedOrPaused);
        }

        private void OnArticleTextToSpeechStartedOrPaused(ArticleTextToSpeechStartedOrPause obj)
        {
            iconPlay.IsEnabled = !obj.Content;
            iconPause.IsEnabled = obj.Content;
        }

        private ArticlePageViewModel VM { get { return (ArticlePageViewModel) ViewModel; } }

        private void OnArticleFocusOnParagraph(ArticleFocusOnParagraphMessage obj)
        {
            var paragraph = obj.Content;
            var container = listBoxParagraphs
                .Items
                .OfType<ListBoxItem>()
                .FirstOrDefault(c => c.DataContext is string && c.DataContext.As<string>() == paragraph);
            
            if (container != null)
            {
                listBoxParagraphs.ScrollIntoView(listBoxParagraphs.Items.Last().As<ListBoxItem>());
                listBoxParagraphs.UpdateLayout();
                container.IsSelected = true;
                //listBoxParagraphs.ScrollIntoView(container);
            }
        }

        private void AppBarPlay(object sender, EventArgs e)
        {
            VM.StartTextToSpeech.Execute(null);
        }

        private void AppBarPause(object sender, EventArgs e)
        {
            VM.PauseTextToSpeech.Execute(null);
        }

        private void AppBarShareViaEmail(object sender, EventArgs e)
        {
            VM.ShareViaEmail.Execute(null);
        }

        private void AppBarShareOnTwitter(object sender, EventArgs e)
        {
            VM.ShareOnTwitter.Execute(null);
        }

        private void AppBarShareOnFacebook(object sender, EventArgs e)
        {
            VM.ShareOnFacebook.Execute(null);
        }
    }
}